package com.itheima.job;

import com.itheima.entity.RedisConst;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

/**
 * @ClassName ClearImageJob
 * @Description: TODO
 * @Author 郑乾
 * @Date 2020-06-25
 * @Version V1.0
 **/
public class ClearImageJob {
    @Autowired
    JedisPool jedisPool;

    public void clearImageJob() {
        //获取所有图片名称
        Set<String> imgNames = jedisPool.getResource().smembers(RedisConst.SETMEAL_PIC_RESOURCES);
        //获取昨天的日期字符串
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        Date yesterday = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String str = sdf.format(yesterday);
        //开始删除
        for (String imgName : imgNames) {
            //如果是昨天的日期开头则可以删除
            if (imgName != null && imgName.startsWith(str)) {
                //删除昨天的图片
                delQiniu(imgName);
                //删除redis中的图片名称
                jedisPool.getResource().srem(RedisConst.SETMEAL_PIC_RESOURCES, imgName);
                System.out.println("删除了" + imgName + "图片");
            }
        }
    }

    private void delQiniu(String imgName) {
        Configuration cfg = new Configuration(Zone.zone0());
        String key = imgName;
        Auth auth = Auth.create("dCz2zbkYrrggeNsyBoZ5qECgGoOKQ4K1jZ49oXL4", "WsKVSX9jn1pYNEIYgThpgJVNSBARFgmQUvFeLVXX");
        BucketManager bucketManager = new BucketManager(auth, cfg);

        try {
            bucketManager.delete("itcast366", key);
            System.out.println("删除成功");
        } catch (QiniuException e) {
            System.out.println("删除时出现异常" + e.code());
            System.out.println(e.response.toString());
        }
    }
}
